<template>
  <div class="container">
    <el-card class="box-card">
      <!-- 按钮区域 -->
      <div class="btn_wrapper">
        <el-button type="success" icon="el-icon-edit" size="small" @click="addQuestion($router.push('new'))">新增试题</el-button>
      </div>
      <!-- 表单和下拉框区域 -->
      <el-form ref="ruleForm" :model="formInline" class="demo-form-inline" label-width="80px" size="mini">

        <!-- 这里需要在学科那边调用接口进行渲染 -->
        <!--   -->
        <el-col :span="6"> <el-form-item label="学科">
          <el-select v-model="questionsList.subjectID" placeholder="请选择" style="width:100%" @change="changeSubject">

            <el-option

              v-for="(item) in subjectList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />

          </el-select>
        </el-form-item></el-col>
        <el-col :span="6">
          <el-form-item label="二级目录">
            <el-select v-model="questionsList.catalogID" placeholder="请选择" style="width:100%">
              <el-option
                v-for="item in directoryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />

            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="标签">
            <el-select v-model="questionsList.tags" placeholder="请选择" style="width:100%">
              <el-option
                v-for="item in tabsOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />

            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <!-- 简单的输入框 -->
          <el-form-item label="关键字">
            <el-input v-model="questionsList.keyword" style="width:100%" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="试题类型">
            <el-select v-model="questionsList.questionType" placeholder="请选择" style="width:100%">
              <el-option
                v-for="item in questionTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />

            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="难度">
            <el-select v-model="questionsList.difficulty" placeholder="请选择" style="width:100%">
              <el-option
                v-for="item in difficultyList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />

            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="方向">
            <el-select v-model="questionsList.direction" placeholder="请选择" style="width:100%">
              <el-option
                v-for="item in directionList"
                :key="item"
                :label="item"
                :value="item"
              />

            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="录入人">
            <el-select v-model="questionsList.creatorID" placeholder="请选择" style="width:100%">
              <el-option
                v-for="item in creatorList"
                :key="item.id"
                :label="item.username"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <!-- 简单的输入框 -->
          <el-form-item label="题目备注">
            <el-input v-model="questionsList.remarks" style="width:100%" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <!-- 简单的输入框 -->
          <el-form-item label="企业简称">
            <el-input v-model="questionsList.shortName" style="width:100%" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="城市">

            <el-select v-model="questionsList.city" placeholder="请选择" style="width:48%; margin-right:2%" @change="handelCity">

              <el-option
                v-for="item in datasList"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>

            <el-select v-model="questionsList.province" placeholder="请选择" style="width:50%">
              <el-option
                v-for="item in areaList"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>

          </el-form-item>
        </el-col>
        <el-col :span="6">
          <!-- 这里是按钮 -->
          <el-form-item style="text-align:right;">

            <el-button @click="clear">清除</el-button>
            <el-button type="primary" @click="filter">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-form>
      <!-- 消息提示,需要绑定自定义属性，变量需要配合属性绑定，属性绑定里面不能使用插槽 -->
      <el-alert
        style="margin-bottom:10px"

        :title="`数据一共${counts}条`"
        type="info"
        show-icon
      />
      <!-- table表格 -->
      <!-- 先渲染下面的数据 -->

      <el-table
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column
          prop="number"
          label="试题编号"
          width="180"
        />
        <el-table-column
          prop="subject"
          label="学科"
          width="180"
        />
        <el-table-column
          prop="catalog"
          label="目录"
        />
        <el-table-column
          prop="questionType"
          :formatter="sfktFormate"
          label="题型"
        />
        <el-table-column

          prop="question"
          label="题干"
        >
          <template #default="{row}">
            <p v-html="row.question" />
          </template>
        </el-table-column>
        <el-table-column

          label="录入时间"
        >
          <template #default="{row}">
            {{ row.addDate|parseTimeByString }}
          </template>
        </el-table-column>
        <el-table-column
          :formatter="difFormate"
          prop="difficulty"
          label="难度"
        />
        <el-table-column
          prop="creator"
          label="录入人"
        />

        <el-table-column label="操作">
          <template #default="{row}">
            <el-button plain type="primary" size="small" circle icon="el-icon-view" title="预览" @click="openPreviewDialog(row)" />
            <el-button plain type="success" size="small" circle icon="el-icon-edit" title="修改" @click="$router.push(`new?id=${row.id}`)" />
            <el-button plain type="danger" size="small" circle icon="el-icon-delete" title="删除" @click="delQuestion(row)" />
            <el-button plain type="warning" size="small" circle icon="el-icon-check" title="加入精选" @click="addChoice(row)" />
          </template>
        </el-table-column>

      </el-table>
      <!-- 分页功能 -->
      <div class="block">
        <el-pagination
          :current-page="questionsList.page"
          :page-sizes="[1, 2, 5, 11]"
          :page-size="questionsList.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="counts"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <!-- 弹窗功能 -->
      <questions-preview
        ref="dialogOpen"
        :dialog-visible.sync="dialogVisible"
        :preview-data="previewData"
      />
    </el-card>

  </div>
</template>

<script>
// 精选题库加入和取消
import { list, remove, choiceAdd } from '../../api/hmmm/questions'
import { difficulty, questionType, direction } from '../../api/hmmm/constants'
// 从学科引入进来的数据
import { simple as subjectList } from '../../api/hmmm/subjects'
import { simple as directoryList } from '../../api/hmmm/directorys'
// 标签列表
import { simple as simpleList } from '../../api/hmmm/tags'
// 录入人
import { simple as creatorList } from '../../api/base/users'
// 城市数据
import { provinces as getCity, citys as getArea } from '@/api/hmmm/citys'
// 引入字组件
import QuestionsPreview from '../components/questions-preview'

// 获取目录
export default {
  name: 'Question',
  components: {
    QuestionsPreview
  },
  data() {
    return {
      // 视频预览对话框
      dialogVisible: false,
      formInline: {
        user: '',
        region: ''
      },
      // 总条数
      counts: 0,
      // 列表渲染的数据
      tableData: [],
      // 学科列表
      subjectList: [],
      // 学科数据
      subjectData: {
        page: 1, // 当前页数
        pagesize: 100 // 一页的个数
      },
      // 目录数据
      directoryOptions: [],
      // 标签的值
      tabsOptions: [],
      // 试题类型
      questionTypeList: [],
      // 试题难度
      difficultyList: [],
      // 方向
      directionList: [],
      // 录入人
      creatorList: [],
      // 城市数据
      datasList: [],

      // 市区数据
      areaList: [],
      // 预览数据
      previewData: {},

      // 当前被选中的值
      current: '',
      questionsList: {
        page: 1, // 当前页数
        pagesize: 5, // 一页的个数
        subjectID: null, // 学科
        difficulty: null, // 难度
        questionType: null, // 试题类型
        tags: null, // 标签名称
        province: null, // 企业所在地省份
        city: null, // 企业所在城市
        keyword: null, // 关键字
        remarks: null, // 题目备注
        shortName: null, // 企业简称
        direction: null, // 方向
        creatorID: null, // 录入人
        catalogID: null // 目录

      }
    }
  },

  // 一进来就渲染页面拿数据
  created() {
    this.getAllList()
    this.selectChange()
    this.questionTypeList = questionType
    // 试题难度
    this.difficultyList = difficulty
    this.directionList = direction
    // 录入人数据
    this.getcreatorList()
    // 城市数据
    this.datasList = getCity()
  },
  methods: {
    onSubmit() {
      console.log('submit!')
    },

    handleSizeChange(val) {
      // 每页的条数
      this.questionsList.pagesize = val
      this.getAllList()
    },
    handleCurrentChange(val) {
      // 当前页数
      this.questionsList.page = val
      this.getAllList()
    },
    // 获取所有数据列表,因为要做分页，所以需要携带参数
    async getAllList() {
      const { data: { counts, items }} = await list(this.questionsList)
      this.counts = counts
      this.tableData = items
    },
    // 将1和2和3渲染成，单选、多选、和简答
    sfktFormate(row) {
      // 先遍历数组 每个都去找到和当前组匹配的，然后将其转换成对应的字符，然后将其return出去
      return questionType.find((item) => { return item.value === +row.questionType }).label
    },
    // 将1和2和3渲染成，简单、一般、和困难
    difFormate(row) {
      return difficulty.find((item) => { return item.value === +row.questionType }).label
    },
    // 删除事件
    delQuestion(row) {
      // console.log('点击了删除事件', id)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 先发请求
        await remove(row)
        // 提示用户（这里有一个小bug删除的话，如果当前页数大于1，并且当前页的size长度=1，让其page--）
        if (this.questionsList.page > 1 && this.questionsList.pagesize === 1) {
          this.page--
        }
        this.$message.success('删除成功')
        // 渲染视图
        this.getAllList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // select下拉框事件
    // 当选择学科后，加载对应的标签列表，渲染其下拉选项
    async selectChange() {
      const { data } = await subjectList(this.subjectData)
      this.subjectList = data
    },
    async changeSubject(subjectID) {
      // 打印的是当前项目的id,如果选择了学科，就可以获取到对应的目录
      this.questionsList.catalogID = null
      this.questionsList.tags = null
      if (subjectID) {
        // 获取目录
        const { data: directoryArr } = await directoryList({ subjectID })
        this.directoryOptions = directoryArr
        // 获取标签
        const { data: tagsArr } = await simpleList({ subjectID })
        this.tabsOptions = tagsArr
      } else {
        this.directoryOptions = []
        this.tagOptions = []
      }
    },
    // 录入人数据
    async getcreatorList() {
      const { data: creator } = await creatorList()
      this.creatorList = creator
    },
    async  handelCity(cityName) {
      // 之前地区选中的数据清空

      const res = await getArea(cityName)
      // 把这个渲染到页面上面
      this.areaList = res
      // 地区里面的值渲染之后，点击清除的时候应该清空
    },
    // 遍历每一项把页数，和每页的个数，取消掉，然后把其余的赋值为null，因为上面的搜索框V-model没有绑定page和page-size
    clear() {
      // for (const key in this.requestParams) {
      //   if (key !== 'page' && key !== 'pagesize') this.requestParams[key] = null
      // }
      // 输入框里面的值为空
      this.questionsList = {
        subjectID: null, // 学科
        difficulty: null, // 难度
        questionType: null, // 试题类型
        tags: null, // 标签名称
        province: null, // 企业所在地省份
        city: null, // 企业所在城市
        keyword: null, // 关键字
        remarks: null, // 题目备注
        shortName: null, // 企业简称
        direction: null, // 方向
        creatorID: null, // 录入人
        catalogID: null // 目录
      }
      // 让二级目录和地区里面的值为空
      // 市区数据
      this.areaList = []
      this.directoryOptions = []
      // 标签里面的值为空
      this.tabsOptions = []
    },
    filter() {
      this.questionsList.page = 1
      this.getAllList()
    },
    // 加入精选
    addChoice(row) {
      this.$confirm('此操作将题目加入精选, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
        // 1代表加入精选，0代表移出精选
      }).then(async() => {
        await choiceAdd({ id: row.id, choiceState: 1 })
        this.$message.success('加入精选成功')
        this.getAllList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消加入精选'
        })
      })
    },
    // 预览功能
    // 让当前点击的这一项上面的值传递过去
    openPreviewDialog(row) {
      this.previewData = row
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.dialogOpen.open()
      })
    }

  }

}
</script>

<style scoped lang='scss'>
.box-card{
  margin: 10px;
}
.btn_wrapper{
  text-align: right;
  margin-bottom: 10px;
}
.block{
  text-align: right;
}

</style>
